package com.denlaku.longan.service.impl;

import com.denlaku.longan.anno.RequiredTx;
import com.denlaku.longan.qo.CustomApiQuery;
import com.denlaku.longan.qo.Query;
import com.denlaku.longan.repository.CustomApiRepository;
import com.denlaku.longan.service.CustomApiFieldService;
import com.denlaku.longan.service.CustomApiService;
import com.denlaku.longan.util.Objects;
import com.denlaku.longan.util.SnowflakeUtils;
import com.denlaku.longan.vo.CustomApi;
import com.denlaku.longan.vo.CustomApiField;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tianx
 */
@Service
public class CustomApiServiceImpl implements CustomApiService {
    @Autowired
    private CustomApiRepository customApiRepository;

    @Autowired
    private CustomApiFieldService customApiFieldService;

    @Override
    @RequiredTx
    public void add(CustomApi customApi) {
        customApi.setId(SnowflakeUtils.nextId());
        customApiRepository.add(customApi);
        addFields(customApi);
    }

    private void addFields(CustomApi customApi) {
        List<CustomApiField> fields = customApi.getFields();
        if (CollectionUtils.isNotEmpty(fields)) {
            for (CustomApiField customApiField : ListUtils.emptyIfNull(fields)) {
                customApiField.setTenantId(customApi.getTenantId());
                customApiField.setApiId(customApi.getId());
                customApiField.setId(SnowflakeUtils.nextId());
            }
            customApiFieldService.batchAdd(fields);
        }
    }

    @Override
    @RequiredTx
    public void update(CustomApi customApi) {
        Long tenantId = customApi.getTenantId();
        Long id = customApi.getId();
        customApiFieldService.delete(tenantId, id);
        addFields(customApi);
        customApiRepository.update(customApi);
    }

    @Override
    @RequiredTx
    public void delete(Query query) {
        customApiRepository.delete(query);
    }

    @Override
    public CustomApi get(Query query) {
        CustomApi customApi = customApiRepository.get(query);
        Objects.ifPresent(customApi, () -> {
            Long tenantId = query.getTenantId();
            Long id = query.getId();
            customApi.setFields(customApiFieldService.list(tenantId, id));
        });
        return customApi;
    }

    @Override
    public List<CustomApi> list(CustomApiQuery query) {
        return customApiRepository.list(query);
    }

}
